package socket.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * TCP 服务端
 */
public class TCPDictServer {
    public ServerSocket serverSocket = null;

    public HashMap<String,String> dictMap = new HashMap<>();
    //对serversocket 进行初始化
    //服务端的ServerSocket 需要指定端口号
    public TCPDictServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
        dictMap.put("cat","猫");
        dictMap.put("dog","狗");
        dictMap.put("pig","猪");
        dictMap.put("fox","狐狸");
        dictMap.put("frog","青蛙");
    }

    //创建一个固定线程数的线程池
    ExecutorService executorService = Executors.newFixedThreadPool(10);

    public void start() throws IOException {
        //1.等待建立连接
        System.out.println("服务端已启动,等待客户端建立连接...");
        //没有客户端请求的话, accept会一直被阻塞, 直到有客户端来请求建立连接
        //clientSocket  就类似餐馆返回给用户的小票
        while (true){
            Socket clientSocket = serverSocket.accept();
            //2.接收数据并处理数据
            executorService.submit(()->{
                process(clientSocket);//此时, 服务端返回Socket, 服务端和客户端已经建立连接
            });

        }

    }

    private void process(Socket clientSocket) {
        System.out.printf("和客户端建立连接[%s:%d]\n",
                clientSocket.getInetAddress().getHostName(),clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream()){
            try(OutputStream outputStream = clientSocket.getOutputStream()) {
                //方便起见, 使用Scanner
                Scanner scanner = new Scanner(inputStream);
                while (true){
                    if (!scanner.hasNext()){
                        System.out.printf("和客户端断开连接[%s:%d]\n",
                                clientSocket.getInetAddress().getHostName(),clientSocket.getPort());
                        break;
                    }
                    String request = scanner.nextLine();

                    //对接收的数据, 进行处理(翻译)
                    String response = processRequest(request);
                    //把响应内容, 返回给客户端
                    PrintWriter writer = new PrintWriter(outputStream);
                    writer.println(response);
                    writer.flush();
                    System.out.printf("接收到客户端发送的数据[%s:%d]:%s,返回响应数据: %s\n",
                            clientSocket.getInetAddress().getHostName(),clientSocket.getPort(),request,response);

                }
            }


        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String processRequest(String request) {
        return dictMap.getOrDefault(request,"无法翻译");
    }

    public static void main(String[] args) throws IOException {
        TCPDictServer server = new TCPDictServer(9090);
        server.start();
    }
}
